package com.yenroc.ho.aspect;

import com.yenroc.ho.annotation.GlobalTransaction;
import com.yenroc.ho.netty.enums.GlobalTransactionType;
import com.yenroc.ho.transaction.GlobalTransactionInfo;
import com.yenroc.ho.transaction.GlobalTransactionManager;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author： heyanpeng
 * @date： 2021/7/27
 */
@Aspect
@Component
public class GlobalTransactionAspect {

    private final Logger log = LoggerFactory.getLogger(GlobalTransactionAspect.class);

    @Around("@annotation(com.yenroc.ho.annotation.GlobalTransaction)")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        log.debug("GlobalTransaction start....");

        String groupId = Thread.currentThread().getName();

        // 创建事务,并且推送到 事务中心
        GlobalTransactionInfo globalTransaction = GlobalTransactionManager.createTransaction();

        try {
            Object proceed = point.proceed();

            // 通知本事务执行完成
            GlobalTransactionManager.sendTransactionResult(globalTransaction, GlobalTransactionType.commit);
            return proceed;
        } catch (Exception e) {
            log.error("业务处理失败,通知事务中心,回滚本组事务===", e);
            // 将事务 添加到事务组
            GlobalTransactionManager.sendTransactionResult(globalTransaction, GlobalTransactionType.rollback);
            throw e;
        }
    }
}
